package cn.stacey.springmvc.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.stacey.springmvc.domain.Category;
import cn.stacey.springmvc.domain.Post;

@Controller
public class PostController {
//http://localhost/springmvc/pages
	@RequestMapping("/pages/list")
	public ModelAndView list() {
		//查询文章所有列表
	List<Post> posts=findPosts();
	//跳转到文章列表对应的jsp页面
	ModelAndView mv=new ModelAndView();//跳到哪个页面（view），页面上需要显示哪些数据（model）
	mv.setViewName("post");
	mv.addObject("posts",posts);
	return mv;
		
	}
	
	//返回json序列化
	@RequestMapping("/pages/jsonlist")
	@ResponseBody
	public List<Post> jsonlist() {
		//查询文章所有列表
	List<Post> posts=findPosts();
	return posts;	
		
	}
	
	
	@RequestMapping("/pages/find_by_id")
	@ResponseBody
	public Post findById(int id) {
		Post post= new Post();
		post.setId(id);
		post.setContent("中文");
		post.setTitle("标题");
		post.setCreated(new Date());
		Category c=new Category();
		c.setId(1);
		c.setName("分类1");
		c.setPriority(2);
		post.setCategory(c);
		return post;
		
	}
	public List<Post> findPosts() {
		List<Post> posts=new ArrayList<>();
		for(int i=0;i<10;i++) {
			Post p=new Post();
			p.setId(i);
			p.setTitle("title"+i);
			p.setContent("content"+i);
			p.setCreated(new Date());
			posts.add(p);
		}
		return posts;
	}
	
	@RequestMapping("/pages/edit_form")
	public String editForm(Model model) {
		model.addAttribute("id",1);
		return "post_form";
	}
	
	
	
	@RequestMapping("/pages/edit")
	public String edit(Post p) {
		System.out.println(p);
		return "success";
		
	}
	
}





